import requests
import threading
import pymysql
import parsel
from threading import Lock
import http.client
import time
newtime=time.strftime('%Y-%m-%d')
conn = pymysql.connect(host='10.10.0.207', port=8306, user='asinuser', password='16Asin@~!1^g902',
                       database='sunway_db', charset='utf8')
cursor = conn.cursor()
lock = Lock()
http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'
http.client.HTTPConnection._http_vsn = 10


def login():
    login_url = 'http://sw.eccang.com/default/index/login'
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Length": "56",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Host": "sw.eccang.com",
        "Origin": "http://sw.eccang.com",
        "Pragma": "no-cache",
        "Referer": "http://sw.eccang.com/default/index/logout?company_code=sw",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4455.2 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
    }
    body = {
        "userName": "jinhuaitao",
        "userPass": "jht834719#",
        # "userName": "huangzhengchao",
        # "userPass": "hzc@123456",
        "companyCode": ""
    }
    try:
        res = requests.post(url=login_url, headers=headers, data=body)
        cookies = res.cookies.items()
        # print(cookies)
        cookie = ''
        for name, value in cookies:
            cookie += '{0}={1};'.format(name, value)
        print('UM_distinctid=17c15b16b7275-02b55430879ff9-2343360-1fa400-17c15b16b7376d;' + cookie)
        return cookie
    except Exception as err:
        print('获取cookie失败：\n{0}'.format(err))


cookies = login()
data = {
    "order_by": "",
    "E10": "",
    "E39": "",
    "ftpo_code": "",
    "input_shipment_id": "",
    "input_tracking_id": "",
    "creater_id": "",
    "ftpoa_shipment_name": "",
    "dateForAdd": "{}".format(newtime),
    "dateToAdd": "{}".format(newtime),
}

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cache-Control': 'no-cache',
    'Content-Length': '152',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Cookie': '{}'.format(cookies),
    'Host': 'sw.eccang.com',
    'Origin': 'http://sw.eccang.com',
    'Pragma': 'no-cache',
    'Proxy-Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
}


def data0():
    # http://sw.eccang.com/transfer/service-transfer-plan-order/list/page/1/pageSize/100
    url = 'http://sw.eccang.com/transfer/fba-transfer-plan-order/list/page/1/pageSize/20'
    res = requests.post(url, headers=headers, data=data, stream=True).json()
    # print(res)
    total = res["total"]
    print(total)
    data1(total)


def data1(total):
    list1 = []
    pages_int = int(int(total) / 100)
    # print(pages)
    # print(pages / 1000)
    if int(total) / 100 > 1:
        # print('大于1')
        if int(total) / 100 - pages_int > 0:
            pages_num = pages_int + 1
            # print('大于2', pages_num)
            list1.append(pages_num)
        else:
            pages_num = pages_int
            # print('整数',pages_num)
            list1.append(pages_num)
    else:
        pages_num = 1
        # print('小于1',pages_num)
        list1.append(pages_num)
    list_ts = []
    # num = 0
    # jim=open('jim.csv','w',encoding='utf-8')

    for j in range(list1[0]):
        # data_duo(j)

        ts = threading.Thread(target=data_duo, args=(j,))
        list_ts.append(ts)

    for i_ts1 in list_ts:
        i_ts1.start()  # 启动线程

    for i_ts in list_ts:
        i_ts.join()  # 关闭线程


def data_duo(j):
    url = f'http://sw.eccang.com/transfer/fba-transfer-plan-order/list/page/{j}/pageSize/100'
    res = requests.post(url, headers=headers, data=data, stream=True).json()
    for i in res["data"]:
        # print(i)
        E1 = i["E1"]  # FBA计划单
        E37 = i["E37"]  # 店铺
        ftpoa_shipment_name = i["ftpoa_shipment_name"]  # 货件名称
        E38 = i["E38"]  # 目标市场
        E10 = i["E10"]  # 计划状态0:草稿1:待审核3:已预报
        deliverStatus = i["deliverStatus"]  # 发货状态
        receivingStatus = i["receivingStatus"]  # 收获状态
        user_name = i["user_name"]  # 备货人
        E28 = i["E28"]  # 备货时间
        E0 = i["E0"]  # id
        print('#' * 30)
        all1 = (E1, E37, ftpoa_shipment_name, E38, E10, deliverStatus, receivingStatus, user_name, E28)
        print(all1)
        lock.acquire()
        mysql_one(E1, E37, ftpoa_shipment_name, E38, E10, deliverStatus, receivingStatus, user_name, E28)
        lock.release()
        data_duo_two(E0, E1)
        if str(E10) == '3':
            data_duo_four(E1, E0)


def data_duo_two(E0, E1):
    url = 'http://sw.eccang.com/transfer/fba-transfer-plan-order/fba-Shipment-List/id/{}'.format(E0)
    res = requests.post(url, headers=headers, data=data, stream=True).json()
    for i in res["data"]:
        ftpos_shipment_id = i["ftpos_shipment_id"]  # ShipmentID
        ftpos_tracking_id = i["ftpos_tracking_id"]  # 货件追踪编号
        ftpos_shipment_name = i["ftpos_shipment_name"]  # 货件名称
        ftpos_sku_category = i["ftpos_sku_category"]  # 卖家SKU种树
        ftpos_sku_count = i["ftpos_sku_count"]  # 数量
        ftpos_shiptoaddress = i["ftpos_shiptoaddress"]  # 目的地
        shipmentDetail = i["shipmentDetail"]
        all2 = (ftpos_shipment_id, ftpos_tracking_id, ftpos_shipment_name, ftpos_sku_category, ftpos_sku_count,
                ftpos_shiptoaddress)
        print(all2)
        lock.acquire()
        mysql_two(ftpos_shipment_id, ftpos_tracking_id, ftpos_shipment_name, ftpos_sku_category, ftpos_sku_count,
                  ftpos_shiptoaddress, E1)
        lock.release()
        data_duo_three(shipmentDetail, ftpos_shipment_id)


def data_duo_three(shipmentDetail, ftpos_shipment_id):
    for i in shipmentDetail:
        warehouse_product_code = i["warehouse_product_code"]  # FNSKU
        product_name = i["product_name"]  # 商品名称
        quantity = i["quantity"]  # 数量
        all3 = (warehouse_product_code, product_name, quantity)
        print(all3)
        lock.acquire()
        mysql_three(warehouse_product_code, product_name, quantity, ftpos_shipment_id)
        lock.release()


def data_duo_four(E1, E0):  # E1,E0
    headers1 = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Cookie": "{}".format(cookies),
        "Host": "sw.eccang.com",
        "Pragma": "no-cache",
        "Referer": "http://sw.eccang.com/?company_code=sw",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36",

    }
    url = 'http://sw.eccang.com/transfer/fba-transfer-plan-order/continue-operation-by-status/id/{}'.format(
        E0)  # 4571,E0
    res = requests.get(url, headers=headers1).content.decode()
    # print(res)
    selector = parsel.Selector(res)
    trs = selector.css('.delivery-type-remark::text').get()
    rd = selector.css('td >label::text').get()
    str1 = rd + trs  # str1是发货方式
    date1 = selector.css('.shipping_info>.search-module-condition >span::text').getall()[1:19]
    # print(date1)
    fbaall1 = []
    fbaall1 = fbaall1 + date1[1::2]
    # print(fbaall1)

    date2 = selector.css('.shipping_info .search-module-condition::text').getall()[-17:]
    # print(date2)
    date2 = str(date2).replace(' ', '').replace('\\n', '')[2:-2].split("','','")
    # print(date2)
    alllist = [str1]
    alllist = alllist + date2 + fbaall1
    print(alllist, len(alllist))
    lock.acquire()
    mysql_four(alllist,E1)
    lock.release()
    # print('*************************************************************')


def mysql_one(E1, E37, ftpoa_shipment_name, E38, E10, deliverStatus, receivingStatus, user_name, E28):
    cursor.execute(
        "REPLACE into eccang_plan_sheet1 set E1=%s,E37=%s,ftpoa_shipment_name=%s,E38=%s,E10=%s,deliverStatus=%s,receivingStatus=%s,user_name=%s,E28=%s",
        [E1, E37, ftpoa_shipment_name, E38, E10, deliverStatus, receivingStatus, user_name, E28])
    conn.commit()


def mysql_two(ftpos_shipment_id, ftpos_tracking_id, ftpos_shipment_name, ftpos_sku_category, ftpos_sku_count,
              ftpos_shiptoaddress, E1):
    cursor.execute(
        "REPLACE into eccang_plan_sheet2 set ftpos_shipment_id=%s,ftpos_tracking_id=%s,ftpos_shipment_name=%s,ftpos_sku_category=%s,ftpos_sku_count=%s,ftpos_shiptoaddress=%s,E1=%s",
        [ftpos_shipment_id, ftpos_tracking_id, ftpos_shipment_name, ftpos_sku_category, ftpos_sku_count,
         ftpos_shiptoaddress, E1])
    conn.commit()


def mysql_three(warehouse_product_code, product_name, quantity, ftpos_shipment_id):
    cursor.execute(
        "REPLACE into eccang_plan_sheet3 set warehouse_product_code=%s,product_name=%s,quantity=%s,ftpos_shipment_id=%s",
        [warehouse_product_code, product_name, quantity, ftpos_shipment_id])
    conn.commit()


def mysql_four(alllist, E1):
    cursor.execute(
        "REPLACE into eccang_plan_sheet4 set str1=%s,str2=%s,str3=%s,str4=%s,str5=%s,str6=%s,str7=%s,str8=%s,str9=%s,str10=%s,str11=%s,str12=%s,str13=%s,str14=%s,str15=%s,str16=%s,str17=%s,str18=%s,str19=%s,E1=%s",
        [alllist[0], alllist[1], alllist[2], alllist[3], alllist[4], alllist[5], alllist[6], alllist[7], alllist[8],
         alllist[9], alllist[10], alllist[11], alllist[12], alllist[13], alllist[14], alllist[15], alllist[16],
         alllist[17], alllist[18], E1])
    conn.commit()


if __name__ == '__main__':
    data0()
